const util = require("../../../utils/util.js");
const db = wx.cloud.database();
var app = getApp();

Page({
  data: {
    delBtnWidth: 90, //删除按钮宽度单位（rpx）
    color: app.ext.color,
    cartData: [], // 购物车数据
    is_edit: 0, // 是否点击编辑SKU按钮
    is_select_all: 1, // 是否全选
    bill_num: 0, // 要结算的商品个数
    deliveryPrice: 0, // 满减
    showSku: false,
    skuHeight: util.rpxToPx(-694) // 购物车弹窗高度
  },
  onLoad: function(options) {},
  onShow: function() {
    this.defaultData();
  },
  defaultData: function() {
    let cartData = wx.getStorageSync("cart-data") ? JSON.parse(wx.getStorageSync('cart-data')) : [];
    if (cartData.length) {
      cartData.forEach(val => {
        if (!val.is_select) {
          this.data.is_select_all = 0;
        }
        val.txtStyle = 'left: 0';
      });
    }
    wx.setStorageSync("cart-data", JSON.stringify(cartData));
    this.setData({
      cartData: cartData,
      is_select_all: this.data.is_select_all
    });
    if (cartData.length) {
      this.getLastPrice();
    }
  },
  // 计算
  getLastPrice() {
    let cartData = JSON.parse(wx.getStorageSync('cart-data'));
    let bill_num = 0;
    let totalPrice = 0;
    let lastPrice = 0;
    cartData.forEach(val => {
      if (val.is_select) {
        bill_num++;
        totalPrice += (val.skuData.length > 0 ? val.skuPrice : val.price) * val.num;
      }
    })
    totalPrice = Number(totalPrice.toFixed(2));
    lastPrice = totalPrice;
    // 计算满减
    // wx.doodoo.fetch(`/shop/api/shop/fullCut/index`).then(res => {
    //   if (res && res.data.errmsg == 'ok' && res.data.data.length) {
    //     let delivery = res.data.data;
    //     let current_delivery = {};
    //     for (let val of delivery) {
    //       if (totalPrice >= val.limit_price) {
    //         this.data.deliveryPrice = val.price;
    //         current_delivery = val;
    //         break;
    //       }
    //     }
    //     lastPrice = totalPrice - this.data.deliveryPrice > 0 ? totalPrice - this.data.deliveryPrice : 0;
    //     lastPrice = Number(lastPrice.toFixed(2));
    //     this.setData({
    //       lastPrice: lastPrice,
    //       current_delivery: current_delivery.id && delivery.length ? current_delivery : delivery[delivery.length - 1]
    //     })
    //   } else {
    //     lastPrice = Number(lastPrice.toFixed(2));
    //     this.setData({
    //       lastPrice: lastPrice,
    //       current_delivery: {}
    //     })
    //   }
    // })
    this.setData({
      lastPrice: lastPrice,
      totalPrice: totalPrice,
      bill_num: bill_num
    })
  },
  // 点击商品左侧的选择按钮
  productSelect: function(e) {
    this.data.is_select_all = 1;
    let item = e.currentTarget.dataset.item;
    let cartData = JSON.parse(wx.getStorageSync('cart-data'));
    cartData.forEach(val => {
      if (val._id == item._id) {
        val.is_select = !val.is_select;
      }
      if (!val.is_select) {
        this.data.is_select_all = 0;
      }
    });
    wx.setStorageSync("cart-data", JSON.stringify(cartData));
    this.setData({
      cartData: cartData,
      is_select_all: this.data.is_select_all
    });
    this.getLastPrice();
  },
  // 点击全选
  selectedAll: function(e) {
    let cartData = JSON.parse(wx.getStorageSync('cart-data'));
    cartData.forEach(val => {
      val.is_select = !val.is_select;
      this.data.is_select_all = val.is_select;
    });
    wx.setStorageSync("cart-data", JSON.stringify(cartData));
    this.setData({
      cartData: cartData,
      is_select_all: this.data.is_select_all
    });
    this.getLastPrice();
  },
  // ---------------------------------------编辑---------------------------------------
  edit: function(e) {
    this.setData({
      is_edit: 1,
      productIndex: e.currentTarget.dataset.product
    });
  },
  hideModal() {
    let _skuHeight = this.data.detailInfo.sku_status ? this.data.skuHeight : util.rpxToPx(-450);
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear'
    })
    animation.translateY(0).step();
    this.setData({
      animationData: animation.export()
    })
    setTimeout(() => {
      animation.translateY(_skuHeight).step();
      this.setData({
        animationData: animation.export(),
        showSku: false
      })
    }, 200)
  },
  showModal(e) {
    this.setData({
      detailInfo: e.currentTarget.dataset.data
    })
    // 0：加入购物车  1：立即购买
    let _skuHeight = this.data.detailInfo.sku_status ? this.data.skuHeight : util.rpxToPx(-450);
    this.data.is_buynow = Number(e.currentTarget.id);
    let animation = wx.createAnimation({
      duration: 200, // 动画持续时间
      timingFunction: 'linear' // 定义动画效果，当前是匀速
    })
    animation.translateY(0).step();
    this.setData({
      animationData: animation.export(), // 通过export()方法导出数据
      showSku: true
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(() => {
      animation.translateY(_skuHeight).step();
      this.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  changeNum(e) {
    const type = e.currentTarget.dataset.id; // 1：减 2：加
    let cart_data = wx.getStorageSync('cart-data') ? JSON.parse(wx.getStorageSync('cart-data')) : [];
    if (type) {
      const detailInfo = e.currentTarget.dataset.item;
      cart_data.forEach(val => {
        if (val._id == detailInfo._id) {
          if (type == 1) {
            if (val.num > 1) {
              val.num--;
            }
          } else {
            val.num++;
          }
        }
      })
    } else {
      const detailInfo = e.detail;
      cart_data.forEach(val => {
        if (val._id == detailInfo._id) {
          val.num = detailInfo.num;
        }
      })
    }
    wx.setStorageSync('cart-data', JSON.stringify(cart_data));
    this.setData({
      cartData: cart_data
    })
    this.getLastPrice();
  },
  buyNowOrAddCart(e) {
    this.hideModal();
    // 0：加入购物车  1：立即购买
    let detailInfo = e.detail;
    let cart_data = wx.getStorageSync('cart-data') ? JSON.parse(wx.getStorageSync('cart-data')) : [];
    cart_data.splice(this.data.productIndex, 1, detailInfo);
    for (let i = 0; i < cart_data.length - 1; i++) {
      for (let j = 0; j < cart_data.length - 1 - i; j++) {
        if (cart_data[j].id == cart_data[j + 1].id && cart_data[j].select_sku.id == cart_data[j + 1].select_sku.id) {
          cart_data[j].num += cart_data[j + 1].num;
          cart_data.splice(j + 1, 1);
        }
      }
    }

    wx.setStorageSync('cart-data', JSON.stringify(cart_data));
    this.setData({
      is_edit: 0,
      cartData: cart_data
    })
  },
  editOver: function(e) {
    this.setData({
      is_edit: 0,
      productIndex: e.currentTarget.dataset.product
    });
  },
  // 到商品详情
  goDetail(e) {
    wx.navigateTo({
      url: `/pages/shop/product/product-detail/index?id=${e.currentTarget.dataset.item.id}`
    });
  },
  // 去凑单
  toScrapeBill: function() {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },
  // -------------------------------------左滑删除--------------------------------------
  touchS: function(e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function(e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      let moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      let disX = this.data.startX - moveX;
      let delBtnWidth = this.data.delBtnWidth;
      let txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "rpx";
        }
      }
      //获取手指触摸的是哪一项
      let product = e.currentTarget.dataset.product;
      let cartData = this.data.cartData;
      cartData[product].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        cartData: cartData
      });
    }
  },
  touchE: function(e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      let endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      let disX = this.data.startX - endX;
      let delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      let txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "rpx" : "left:0px";
      //获取手指触摸的是哪一项
      let product = e.currentTarget.dataset.product;
      let cartData = this.data.cartData;
      cartData[product].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        cartData: cartData
      });
    }
  },
  delItem: function(e) {
    let item = e.currentTarget.dataset.item;
    let cartData = JSON.parse(wx.getStorageSync('cart-data'));
    cartData.forEach((val, i) => {
      if (val.id == item.id && val.select_sku.id == item.select_sku.id) {
        cartData.splice(i, 1);
      }
    });
    wx.setStorageSync("cart-data", JSON.stringify(cartData));
    this.setData({
      cartData: cartData
    });
    this.getLastPrice();
  },
  // ---------------------------------------结算---------------------------------------
  Bill: function() {
    wx.navigateTo({
      url: `/pages/shop/order/order-add/index?form_cart=1`
    });
  }
})